﻿using B.S.NewMedical.Api.Write.Application.Command.Order.Medicine;
using B.S.NewMedical.Domain.Order;
using B.S.NewMedical.ErrorCode;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.NewMedical.Api.Write.Application.Handler.Order.Medicine
{
    /// <summary>
    /// 删除药品处理器
    /// </summary>
    public class DeleteMedicineCommandHandle : IRequestHandler<DeleteMedicineCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<MedicineModel> _medicineRepository;
        private readonly ILogger<DeleteMedicineCommandHandle> _logger;

        public DeleteMedicineCommandHandle(
            IBaseRepository<MedicineModel> medicineRepository,
            ILogger<DeleteMedicineCommandHandle> logger)
        {
            _medicineRepository = medicineRepository;
            _logger = logger;
        }

        public async Task<ApiResult<int>> Handle(DeleteMedicineCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>();

            try
            {
                _logger.LogInformation("开始删除药品记录，ID：{Id}", request.Id);

                // 1. 查找要删除的药品记录
                var medicine = _medicineRepository.GetAll()
                    .FirstOrDefault(x => x.Id == request.Id && !x.IsDeleted);

                if (medicine == null)
                {
                    result.Code = ApiEnum.Fail;
                    result.Msg = "未找到要删除的药品记录";
                    _logger.LogWarning("未找到要删除的药品记录，ID：{Id}", request.Id);
                    return result;
                }

                // 2. 检查药品记录状态，防止删除已完成的订单
                if (!string.IsNullOrEmpty(medicine.Orderstatus) && 
                    medicine.Orderstatus.Equals("已完成", StringComparison.OrdinalIgnoreCase))
                {
                    result.Code = ApiEnum.Fail;
                    result.Msg = "已完成的药品订单不能删除";
                    _logger.LogWarning("尝试删除已完成的药品订单，ID：{Id}，状态：{Status}", 
                        request.Id, medicine.Orderstatus);
                    return result;
                }

                // 3. 检查药品记录状态，防止删除已发货的订单
                if (!string.IsNullOrEmpty(medicine.Orderstatus) && 
                    medicine.Orderstatus.Equals("已发货", StringComparison.OrdinalIgnoreCase))
                {
                    result.Code = ApiEnum.Fail;
                    result.Msg = "已发货的药品订单不能删除";
                    _logger.LogWarning("尝试删除已发货的药品订单，ID：{Id}，状态：{Status}", 
                        request.Id, medicine.Orderstatus);
                    return result;
                }

                // 4. 执行逻辑删除
                medicine.IsDeleted = true;
                medicine.UpdateTime = DateTime.Now;

                // 5. 更新数据库
                var updateResult = await _medicineRepository.UpdateAsync(medicine);

                if (updateResult > 0)
                {
                    result.Code = ApiEnum.Success;
                    result.Msg = "药品记录删除成功";
                    result.Data = updateResult;
                    
                    _logger.LogInformation("药品记录删除成功，ID：{Id}，订单号：{OrderId}，收货人：{Consignee}，金额：{Amount}", 
                        medicine.Id, medicine.OrderId, medicine.Consignee, medicine.DrugPrices);
                }
                else
                {
                    result.Code = ApiEnum.Fail;
                    result.Msg = "药品记录删除失败";
                    result.Data = updateResult;
                    
                    _logger.LogError("药品记录删除失败，ID：{Id}", request.Id);
                }
            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.Error;
                result.Msg = $"删除药品记录时发生异常：{ex.Message}";
                
                _logger.LogError(ex, "删除药品记录时发生异常，ID：{Id}，异常信息：{Message}", 
                    request.Id, ex.Message);
            }

            return result;
        }
    }
}
